//
//  WaterForumSectionVC.m
//  sensen_ios
//
//  Created by justiOS on 16/5/4.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "WaterForumSectionVC.h"
#import "SendPostVC.h" // 发表帖子页面
#import "PostDetailVC.h"//帖子详情页面
/*
 布局类
 */
#import "PostCellFrameLayout.h" // 帖子概览布局类
#import "ForumModel.h"
#import "SeletedButton.h"
/*
 视图（单元格、自定义）
 */
#import "PostBrowseCell.h" // 帖子概览单元格

@interface WaterForumSectionVC ()<UITableViewDataSource, UITableViewDelegate,refreshDelegate>
{
    UIScrollView *_scrollView;//顶部滑动视图
    UITableView *_tableView; // 表视图
    BOOL _isMoreShow; // 置顶帖是否全部展示
    NSInteger _page; //用于换页加载
    NSInteger _maxNub;
    UIImageView *_lineImage;
    NSInteger nuber;
    NSMutableArray *_fidAry;//用于储存fid
}
/*
 数据
 */
@property (nonatomic, strong) NSMutableArray *itemsAry; // 普通帖子数组
@property (nonatomic, strong) NSMutableArray *topItemsAry; // 置顶帖子数组
@property (nonatomic,strong) SeletedButton *selectedButton; //当前选中的标签栏按钮
@end

@implementation WaterForumSectionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = _naviTitle; // 设置导航栏标题
    _itemsAry = [[NSMutableArray alloc] initWithCapacity:5];
    _fidAry = [[NSMutableArray alloc] initWithCapacity:5];
    _page = 1;
    _maxNub = 0;
    [self createLeftBarButtonItemWithImagename:nil]; // 设置导航栏返回按钮
    [self _createViews]; // 创建视图
    [self _getNewData]; // 获取数据
    //刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_getNewData)];
    _tableView.header = header;
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;
    //添加手势
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(_swipAction:)];
    swip.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swip];
    UISwipeGestureRecognizer *swip2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(_swipAction:)];
    swip2.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swip2];

}
//添加手势动作方法
- (void)_swipAction:(UISwipeGestureRecognizer *)swip{
    switch (swip.direction) {
        case UISwipeGestureRecognizerDirectionLeft:{
            [self _leftAction];
        }
            break;
        case UISwipeGestureRecognizerDirectionRight:{
            [self _rightAction];
        }
            break;
       
        default:
            break;
    }
}

//左移
- (void)_leftAction{
    if (nuber >0) {
        nuber = nuber - 1;
        ForumModel *model = [[ForumModel alloc] init];
        model = _subForumAry[nuber];
        [self _buttonAction:(SeletedButton *)[_scrollView viewWithTag:(nuber + 10)]];
        
    }
}
//右移
- (void)_rightAction{
    if (nuber < _subForumAry.count - 1) {
        nuber = nuber + 1;
        ForumModel *model = [[ForumModel alloc] init];
        model = _subForumAry[nuber];
        [self _buttonAction:(SeletedButton *)[_scrollView viewWithTag:(nuber + 10)]];

    }
    }
- (void)refreshVC {
    [self _getNewData];
}

- (void)_createScrollView{
    CGFloat x = 0;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = width / 4.0;
    CGFloat y = 0;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _scrollView.contentSize = CGSizeMake(height * 6, 0);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollView];
    
    for (NSInteger i = 0; i < _subForumAry.count; i++) {
        ForumModel *model = [[ForumModel alloc] init];
        model = _subForumAry[i];
        NSString *name = [NSString stringWithFormat:@"%@1",model.name];
        //未选中图片
        UIImage *buttonImage = [UIImage imageNamed:name];
        //选中图片
        UIImage *selectedImage = [UIImage imageNamed:model.name];
        SeletedButton *button = [[SeletedButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 4, 0, SCREEN_WIDTH / 4, SCREEN_WIDTH / 4) Image:buttonImage SelectedImage:selectedImage Title:model.name];
        button.tag = 10 + i;
        [button addTarget:self action:@selector(_buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:button];
        if (button.tag == 10) {
            //刚开始设置第一个按钮为选中按钮
            button.isSelectedButton = YES;
            self.selectedButton = button;
            nuber = 0;
        }
        NSString *fidnum = model.fid;
        [_fidAry addObject:fidnum];
    }
    _lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH / 4 - 20, 1.5)];
    _lineImage.image = [UIImage imageNamed:@"论坛-蓝线"];
    _lineImage.bottom = _scrollView.bottom;
    [_scrollView addSubview:_lineImage];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    [self _getNewData];// 获取数据
    
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
}
#pragma mark - 获取数据


- (void)_getNewData{
    _page = 1;
    [self _pushData];
    [_tableView.header endRefreshing];
    [_tableView.footer resetNoMoreData];
}
- (void)_pushData{
    // 初始化数据数组
    if (_itemsAry == nil) {
        _itemsAry = [[NSMutableArray alloc] init];
    } else {
        [_itemsAry removeAllObjects];
    }
    [SVProgressHUD showWithStatus:@"请耐心等待..."]; // 请求中
    self.view.userInteractionEnabled = NO;
    NSString *pageSize = @"10";
    NSString *stick = @"1";
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_ForumThread_query" apiVerson:100 params:@{@"fid" : _fid ,@"page_size": pageSize ,@"stick" : stick} success:^(AFHTTPRequestOperation *operation, id result) {
        if (weakSelf.topItemsAry == nil) {
            weakSelf.topItemsAry = [NSMutableArray array];
        }else{
            [weakSelf.topItemsAry removeAllObjects];
        }
        if(![result[@"list"] isKindOfClass:[NSNull class]]){
            // 置顶帖子数组赋值
            for (NSDictionary *resultDic in result[@"list"])
            {
                PostModel *model = [[PostModel alloc] initContentWithDic:resultDic];
                [_topItemsAry addObject:model];
            }
        }
        NSString *pageNo = [NSString stringWithFormat:@"%ld",(long)_page];
        [BoyeHttpClient post:@"BY_ForumThread_query" apiVerson:100 params:@{@"fid" : _fid ,@"page_size": pageSize , @"page_no" : pageNo} success:^(AFHTTPRequestOperation *operation, id result) {
            if(![result[@"list"] isKindOfClass:[NSNull class]]){
                NSArray *array = result[@"list"];
                NSString *nub = result[@"count"];
                NSInteger nubInt = [nub intValue];
                for (NSDictionary *resultDic in array) {
                    PostModel *model = [[PostModel alloc] initContentWithDic:resultDic];
                    PostCellFrameLayout *layout = [[PostCellFrameLayout alloc] init];
                    layout.cellType = ZKCellBrowse;
                    layout.model = model;
                    [_itemsAry addObject:layout];
                }
                self.view.userInteractionEnabled = YES;
                if (_itemsAry.count == nubInt) {
                    [_tableView.footer noticeNoMoreData];
                }
            }
            [_tableView reloadData];
            [SVProgressHUD dismiss];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            self.view.userInteractionEnabled = YES;
            [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];
}
- (void)_getMoreData{
    _page = _page + 1; //每次刷新 请求的页的页数编号增加
    [self _createData];
}
- (void)_createData{
    
    NSString *pageSize = @"10";
    NSInteger maxP = 500; //最多显示的帖子数目
    NSMutableArray *mAry = [[NSMutableArray alloc] initWithCapacity:1];
    NSString *pageNo = [NSString stringWithFormat:@"%ld",_page];
    [BoyeHttpClient post:@"BY_ForumThread_query" apiVerson:100 params:@{@"fid" : _fid ,@"page_size": pageSize , @"page_no" : pageNo} success:^(AFHTTPRequestOperation *operation, id result) {
        if(![result[@"list"] isKindOfClass:[NSNull class]]){
            NSArray *array = result[@"list"];
            NSString *nub = result[@"count"];
            NSInteger nubInt = [nub intValue];
            for (NSInteger i = 0; i < array.count; i++)
            {
                NSDictionary *resultDic = array[i];
                PostModel *model = [[PostModel alloc] initContentWithDic:resultDic];
                PostCellFrameLayout *layout = [[PostCellFrameLayout alloc] init];
                layout.cellType = ZKCellBrowse;
                layout.model = model;
                if (_itemsAry.count >= maxP) {
                    [mAry addObject:layout];
                }
                [_itemsAry addObject:layout];
            }
            if (_itemsAry.count > maxP) {
                [_itemsAry removeAllObjects];
                [_itemsAry addObjectsFromArray:mAry];
                [_tableView reloadData];
                [_tableView.footer endRefreshing];
                [_tableView setContentOffset:CGPointZero animated:YES];
                _maxNub = _maxNub + 1;
            }else{
                [_tableView reloadData];
                [_tableView.footer endRefreshing];
                
            }
            if ((_itemsAry.count + _maxNub * maxP) == nubInt) {
                [_tableView.footer noticeNoMoreData];
            }
        }
    }
                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                     [_tableView.footer endRefreshing];
                     [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
                 }];
    
}

#pragma mark - 创建视图
- (void)_createViews {
    [self _createTableView]; // 表视图
    [self _createScrollView];
    [self _createRightBarButtonItems];//右侧导航栏按钮
}


//创建右侧导航栏按钮
- (void)_createRightBarButtonItems{
    
    UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    publishButton.frame = CGRectMake(0, 0, 25, 25);
    [publishButton setBackgroundImage:[UIImage imageNamed:@"论坛首页_发表"] forState:UIControlStateNormal];
    [publishButton addTarget:self action:@selector(_naviRightAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    
    self.navigationItem.rightBarButtonItems = @[barButtonItem];
    
}


//右导航栏按钮点击事件
- (void)_naviRightAction:(UIButton *)button{
    UserModel *user = [CommonCache getUserInfo];
    if(user != nil){
        if (([user.allowpost integerValue] == 0) && (([user.fid integerValue] == [_fid integerValue])||([user.fid integerValue] == 0))) {
            [SVProgressHUD showErrorWithStatus:@"您已经被禁言，暂时无法发言" withDuration:1.5];
            return;
        }else{
            SendPostVC *vc = [[SendPostVC alloc] init];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
            vc.fid = _fid;
        }
    }else if(user == nil){
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVc animated:YES completion:nil];
    }
}

// 创建表视图
- (void)_createTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 4 - 10, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - SCREEN_WIDTH / 4) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    // 注册单元格
    [_tableView registerClass:[PostBrowseCell class] forCellReuseIdentifier:@"PostBrowseCell"];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _itemsAry.count + 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        // 置顶帖小于等于3就不用箭头了，且有几个帖子就是几行
        if (_topItemsAry.count <= 3) {
            return _topItemsAry.count;
        }
        // 置顶帖大于3，则需要多加一行箭头，用于加载更多
        else {
            if (_isMoreShow) { // 需要展示更多
                return _topItemsAry.count + 1; // 还有一栏是箭头
            } else {
                return 4;
            }
        }
    } else {
        return 1;
    }
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 第一组：置顶帖
    if (indexPath.section == 0) {
        // 小于3，说明是置顶帖
        if (indexPath.row < (_isMoreShow ? _topItemsAry.count : 3)) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopPostCell"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TopPostCell"];
                // 置顶图片
                UIImageView *imgView = [[UIImageView alloc] init];
                imgView.userInteractionEnabled = YES;
                imgView.frame = CGRectMake(10, 0, 40, 40);
                imgView.image = [UIImage imageNamed:@"论坛_置顶3"];
                [cell addSubview:imgView];
                // 置顶帖内容
                UILabel *label = [[UILabel alloc] init];
                label.numberOfLines = 0;
                label.frame = CGRectMake(imgView.right + 10, 0, SCREEN_WIDTH - imgView.right - 20, 40);
                label.userInteractionEnabled = YES;
                label.font = FONT(14);
                label.text = @"";
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentLeft;
                [cell addSubview:label];
                label.tag = 1000;
            }
            // 填充数据
            PostModel *model = _topItemsAry[indexPath.row];
            UILabel *label = (UILabel *)[cell viewWithTag:1000];
            label.text = model.postTitle;
            return cell;
        }
        // 大于三，则说明箭头单元格
        else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MorePostCell"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MorePostCell"];
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45 / 2.0, 25 / 2.0)];
                imgView.userInteractionEnabled = YES;
                imgView.image = [UIImage imageNamed:@"论坛_进入论坛_向下"];
                [cell addSubview:imgView];
                imgView.center = CGPointMake(SCREEN_WIDTH / 2, 20);
            }
            return cell;
        }
        
    }
    // 不是第一组，则是普通帖
    else {
        PostBrowseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostBrowseCell"];
        // 填充数据
        if (cell == nil) {
            cell = [[PostBrowseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PostBrowseCell"];
        }
        if (_itemsAry.count != 0) {
            PostCellFrameLayout *layout = _itemsAry[indexPath.section - 1];
            cell.layout = layout;
        }
        return cell;
    }
    
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 40;
    } else {
        if (_itemsAry.count != 0) {
            PostCellFrameLayout *layout = _itemsAry[indexPath.section - 1];
            return layout.cellRect.size.height;
        }else{
            return 0;
        }
        
    }
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *basalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    basalView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:0.5];
    return basalView;
}

// 设置组尾高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

// 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    // 点击箭头
    if (indexPath.section == 0) {
        // 箭头
        if (indexPath.row == (_isMoreShow ? _topItemsAry.count : 3)) {
            _isMoreShow = !_isMoreShow;
            // 刷新第一组的单元格
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
            [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        }else{
            PostDetailVC *vc = [[PostDetailVC alloc] init];
            PostModel *model = _topItemsAry[indexPath.row];
            vc.tid = model.tid;
            vc.fid = model.fid;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else {
        PostDetailVC *vc = [[PostDetailVC alloc] init];
        PostCellFrameLayout *layout = _itemsAry[indexPath.section - 1];
        vc.tid = layout.model.tid;
        vc.fid = layout.model.fid;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}
#pragma make 点击跳转数据
- (void)_buttonAction:(SeletedButton *)button{
    //上一次选中的按钮状态改为no
    self.selectedButton.isSelectedButton = NO;
    //当前被点击的按钮状态改为yes
    button.isSelectedButton = YES;
    //记录当前选中按钮
    self.selectedButton = button;
    _fid = _fidAry[button.tag - 10];
    [self _getNewData];
    [UIView animateWithDuration:0.3 animations:^{
        _lineImage.center = button.center;
        _lineImage.bottom = _scrollView.bottom;

        }];
    nuber = button.tag - 10;
    NSLog(@"%f====%ld\n %f",_scrollView.contentOffset.x,(long)button.tag,_lineImage.center.x);
    if (_lineImage.center.x > 0) {
        [_scrollView setContentOffset:CGPointZero animated:YES];
        if (_lineImage.center.x > (SCREEN_WIDTH * 3 / 4)) {
            [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH / 4, 0) animated:YES];
            if (_lineImage.center.x > SCREEN_WIDTH) {
                [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH / 2, 0) animated:YES];
            }
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
